#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include <iostream>

int main() {
    SQLHENV henv;
    SQLHDBC hdbc;
    SQLHSTMT hstmt;
    SQLRETURN ret;

    // 分配环境句柄
    ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
    if (ret!= SQL_SUCCESS && ret!= SQL_SUCCESS_WITH_INFO) {
        std::cerr << "SQLAllocHandle (ENV) failed" << std::endl;
        return 1;
    }

    // 设置环境属性
    ret = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);
    if (ret!= SQL_SUCCESS && ret!= SQL_SUCCESS_WITH_INFO) {
        std::cerr << "SQLSetEnvAttr failed" << std::endl;
        SQLFreeHandle(SQL_HANDLE_ENV, henv);
        return 1;
    }

    // 分配连接句柄
    ret = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
    if (ret!= SQL_SUCCESS && ret!= SQL_SUCCESS_WITH_INFO) {
        std::cerr << "SQLAllocHandle (DBC) failed" << std::endl;
        SQLFreeHandle(SQL_HANDLE_ENV, henv);
        return 1;
    }

    // 连接到数据库
    ret = SQLConnect(hdbc, (SQLCHAR*)"test_odbc_mysql", SQL_NTS, (SQLCHAR*)"root", SQL_NTS, (SQLCHAR*)"123456", SQL_NTS);
    if (ret!= SQL_SUCCESS && ret!= SQL_SUCCESS_WITH_INFO) {
        std::cerr << "SQLConnect failed" << std::endl;
        SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
        SQLFreeHandle(SQL_HANDLE_ENV, henv);
        return 1;
    }

    // 分配语句句柄
    ret = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
    if (ret!= SQL_SUCCESS && ret!= SQL_SUCCESS_WITH_INFO) {
        std::cerr << "SQLAllocHandle (STMT) failed" << std::endl;
        SQLDisconnect(hdbc);
        SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
        SQLFreeHandle(SQL_HANDLE_ENV, henv);
        return 1;
    }

    // 执行查询语句
    ret = SQLExecDirect(hstmt, (SQLCHAR*)"SELECT * FROM tb_user", SQL_NTS);
    if (ret!= SQL_SUCCESS && ret!= SQL_SUCCESS_WITH_INFO) {
        std::cerr << "SQLExecDirect failed" << std::endl;
        SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
        SQLDisconnect(hdbc);
        SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
        SQLFreeHandle(SQL_HANDLE_ENV, henv);
        return 1;
    }

    // 处理结果集（这里简单打印）
    SQLSMALLINT numCols;
    SQLNumResultCols(hstmt, &numCols);
    // 处理结果集--中文打印不了
    SQLCHAR buffer[1024];
    SQLLEN cbBuffer;
    while (SQLFetch(hstmt) == SQL_SUCCESS) {
        for (SQLSMALLINT i = 1; i <= numCols; i++) {
            SQLGetData(hstmt, i, SQL_C_CHAR, buffer, sizeof(buffer), &cbBuffer);
            std::cout << buffer << " ";
        }
        std::cout << std::endl;
    }
    // 释放语句句柄
    SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
    // 断开连接
    SQLDisconnect(hdbc);
    // 释放连接句柄
    SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
    // 释放环境句柄
    SQLFreeHandle(SQL_HANDLE_ENV, henv);

    return 0;
}
